package com.simpleframe.validator;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.simpleframe.exception.SimpleValidtorException;
import com.simpleframe.util.StringUtil;
import com.simpleframe.util.Utils;
import com.simpleframe.web.ActionMessage;

public class FieldsValidator {

	private ActionMessage actionMessage;
	
	public FieldsValidator(ActionMessage actionMessage){
		this.actionMessage = actionMessage;
	}
	
	//数据验证和提示部分
	
	public void notNull(Object obj, String message){
		if(Utils.isNull(obj)){
			actionMessage.addError(message);
		}
	}
	
	public void notEmpty(String str, String message){
		if(str!=null){
			str = str.trim();
		}
		if(StringUtils.isEmpty(str)){
			actionMessage.addError(message);
		}
	}
	
	public void notZero(Number number, String message){
		if(number==null || 
				number.equals(0)){
			actionMessage.addError(message);
		}
	}
	
	public void notNumber(String str, String message){
		if(!NumberUtils.isNumber(str)){
			actionMessage.addError(message);
		}
	}
	
	public void lessThan(Integer field, Integer number, String message ) {
		if(field==null || field<number){
			actionMessage.addError(message);
		}
	}
	
	public void lessThan(Float field, Float number, String message ) {
		if(field==null || field<number){
			actionMessage.addError(message);
		}
	}
	
	public void lessThan(Double field, Double number, String message ) {
		if(field==null || field<number){
			actionMessage.addError(message);
		}
	}
	
	public void limit(Float field, Double after, Double before, String message ) {
		if(field==null || (field>before || field<after)){
			actionMessage.addError(message);
		}
	}
	
	public void limit(Double field, Double after, Double before, String message ) {
		if(field==null || (field>before && field<after)){
			actionMessage.addError(message);
		}
	}
	
	public void limit(String field, int after, int before, String message ) {
		if(field==null
			 || (field.length()>before || field.length()<after)){
			actionMessage.addError(message);
		}
	}

	public void email(String email, String message){
		
		if(email==null || !email.matches("\\w{1,}[@][\\w\\-]{1,}([.]([\\w\\-]{1,})){1,3}$")){
			actionMessage.addError(message);
		}
	}
	
	public void max(String field, int length, String message){
		notEmpty(field, message);
		if(field.length() > length){
			actionMessage.addError(message);
		}
	}
	
	public void min(String field, int length, String message){
		if(field == null || field.length() < length){
			actionMessage.addError(message);
		}
	}

	public void validator() {
		if(actionMessage.hasError()){
			throw new SimpleValidtorException("asdfasfas");
		}
	}
}
